<?php
/**
 * Author Yulin
 * Email  dwzhanglong@126.com
 * Date   2017-7-21
 * Func   帐变报表
 */
defined('IN_YuLin') || exit('NO PERMIT!');

UserLogin(U($m.'/'.$c.'/'.$a));

$table = Table('user_money_log');
$ttable = Table('user_money_type');

$data  = [];
$where = ' FROM '.$table.' t LEFT JOIN '.$ttable.' tt ON t.tid = tt.tid WHERE t.uid = '.$_uid;

//	玩法
$tids = [];
$tids2 = $_GET['tids'];
if($tids2)
{
	$tids = is_array($tids2) ? $tids2 : explode(',',$tids2);
	
	foreach($tids as $val)
	{
		$tids[] = NoBadStr($val);
	}
	
	$tids && $where .= ' AND t.tid IN (\''.implode('\',\'',$tids).'\')';
}

$dt = NoBadStr($_GET['dtrange']);
$dt = explode(' - ',$dt);
!$dt[0] && $dt[0] = date('Y-m-d',strtotime('-1 day'));
!$dt[1] && $dt[1] = date('Y-m-d');
$dtrange = implode(' - ',$dt);

$where .= ' AND t.dateline >= '.strtotime($dt[0]).' AND t.dateline < '.(strtotime($dt[1]) + 86400);

$page = max(1,intval($_GET['page']));
$size = max(20,intval($_GET['size']));

//	统计
$num = ['income'=>0,'expend'=>0,'income2'=>0,'expend2'=>0];

$tmp = $db->getrow('SELECT COUNT(1) AS p '.$where);
if($tmp['p'])
{
	$orderby = ' ORDER BY t.id DESC ';
	$limit = ' LIMIT '.($page - 1) * $size.','.$size;
	
	$data = $db->getall('SELECT t.*,tt.name '.$where.$orderby.$limit);
	foreach($data as $key => $val)
	{
		$data[$key]['income'] = $data[$key]['expend'] = 0;
		
		if($val['total'] > $val['total_old'])	//	收入
		{
			$data[$key]['income'] = $val['total'] - $val['total_old'];
			$num['income'] += $data[$key]['income'];
		}
		else
		{
			$data[$key]['expend'] = $val['total_old'] - $val['total'];
			$num['expend'] += $data[$key]['expend'];
		}
	}
	
	$url = U($m.'/'.$c,['dtrange'=>$dtrange,'tids'=>implode(',',$tids),'pid'=>$pid,'status'=>$status]);
	$multi = Multi($url,$page,$tmp['p'],$size);
	$total = $tmp['p'];
	
	$tmp = $db->getrow('SELECT SUM(total - total_old) AS money '.$where.' AND total > total_old');
	$num['income'] = round($tmp['money'],2);
	$tmp = $db->getrow('SELECT SUM(total_old - total) AS money '.$where.' AND total_old > total');
	$num['expend'] = round($tmp['money'],2);
}

$head['title'] = '帐变报表';

$tpl->display('member/money');